package com.example.controller;

import cn.hutool.core.map.MapUtil;
import com.example.POJO.Blog;
import com.example.POJO.User;
import com.example.Util.JwtUtils;
import com.example.common.Result;
import com.example.common.dto.LoginDto;
import com.example.repository.BlogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value="/blogs"  )
public class Blogs {

    @Autowired
    BlogRepository blogRepository;

    @Autowired
    JwtUtils jwtUtils;

////    @RequestMapping(value="", method= RequestMethod.GET    )
//    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
//        List<Blog> blogList = blogMapper.Get_blog();
//        return Result.succ(blogList);
//    }


    @RequestMapping(value="", method= RequestMethod.GET    )
    public ResponseEntity  lists(@RequestParam(defaultValue = "0") Integer currentPage, @RequestParam(defaultValue = "3") Integer pageSize){
        if(currentPage > 0){
            currentPage--;
        }
        try {
            Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.Direction.DESC, "id");
            Page<Blog> result = blogRepository.findAll(pageable);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogRepository.getById(id);
        Assert.notNull(blog, "该博客已被删除");
        return Result.succ(blog);
    }




//    @Transactional
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        System.out.println(blog);
        if (blog.getId() == null){
            Integer ii = blogRepository.add_blog(blog.getUserId(), blog.getTitle(), blog.getDescription(), blog.getContent());
            return Result.succ(null);
        }
        Integer count = blogRepository.update_myself(blog.getTitle(), blog.getDescription(), blog.getContent(), blog.getId(), blog.getUserId());
        return Result.succ(null);
    }
}
